import PIL.Image
import os
# from pngquant.pngquantTool import pngquant_compress
# from pngquant.pngquantTool import cmdPngquantCompress
# import numpy as np
# import cv2


def get_size(file):
    # 获取文件大小:KB
    size = os.path.getsize(file)
    return size / 1024


def zipPNG(path: str):
    img = PIL.Image.open(path)
    img.save(path.replace(".png", "new.png"), quality=0, format='PNG')


def zipPNGs(path: str):
    for i in os.listdir(path):
        if ".png" in str(i):
            img = PIL.Image.open(path + i)
            img.save(path + i, quality=0, format='PNG')


def PNG_JPG(path: str):
    """https://www.cnblogs.com/ghgxj/p/14219120.html"""
    im = PIL.Image.open(path)
    im = im.convert('RGB')
    im.save(path.replace(".png", ".jpg"), quality=25)


def PNG_JPGs(path: str):
    """https://www.cnblogs.com/ghgxj/p/14219120.html"""
    for i in os.listdir(path):
        if ".png" in str(i):
            im = PIL.Image.open(path + i)
            im = im.convert('RGB')
            im.save(path + i.replace(".png", ".jpg"), quality=15)


def PNG_JPGs2(path: str):
    """https://www.cnblogs.com/ghgxj/p/14219120.html"""
    for i in os.listdir(path):
        if ".png" in str(i):
            im = PIL.Image.open(path + i)
            im = im.convert('RGB')
            im.save(path + i.replace(".png", ".jpg"), quality=15)


def JPG_PNG(path: str):
    """
    ————————————————
    版权声明：本文为CSDN博主「深度学习与图像目标检测」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
    原文链接：https://blog.csdn.net/weixin_39153202/article/details/96566897"""
    PIL.Image.open(path).convert('RGBA').resize((1920, 1080)).save(path.replace(".jpg", "h.png"), quality=1)


def JPG_PNGs(path: str):
    """
    ————————————————
    版权声明：本文为CSDN博主「深度学习与图像目标检测」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
    原文链接：https://blog.csdn.net/weixin_39153202/article/details/96566897"""
    for i in os.listdir(path):
        if ".jpg" in str(i):
            nm = get_size(path + str(i).replace(".jpg", ".png"))
            PIL.Image.open(path + i).convert('RGBA').resize((1920, 1080))\
                .save(path + "m" + i.replace(".jpg", ".png"), quality=1)
            mm = get_size(path + "m" + i.replace(".jpg", ".png"))
            if nm < mm:  # 留下没m的
                os.remove(path + "m" + i.replace(".jpg", ".png"))
                with open(path + i.replace(".jpg", ".png"), 'rb') as r:
                    read = r.read()
                with open(path + "m" + i.replace(".jpg", ".png"), "wb") as w:
                    w.write(read)
            else:
                os.remove(path + i.replace(".jpg", ".png"))


def integratedOperation(path: str):
    PNG_JPGs(path)
    print("f1")
    JPG_PNGs(path)
    print("f2")
    # zipPNGs(path)
    # print("f3")
    for i in os.listdir(path):
        if ".jpg" in str(i):
            os.remove(path + i)
        if ".png" in str(i) and str(i)[0] != "m":
            os.remove(path + i)
    print("f3")
    PNG_JPGs2(path)
    print("f4")
    for i in os.listdir(path):
        if ".png" in str(i) and str(i)[0] != "m":
            os.remove(path + i)
    print("f5")
    JPG_PNGs(path)
    print("f6")
    for i in os.listdir(path):
        if ".jpg" in str(i):
            os.remove(path + i)
        if ".png" in str(i) and str(i)[0] != "m":
            os.remove(path + i)
    print("f7")
    for i in os.listdir(path):
        if "mm" in str(i):
            print(path + i)
            print(path + i.replace("mm", "m"))  # m路径:path + i.replace("mm", "m")
            try:
                mm = get_size(path + i)
                m = get_size(path + i.replace("mm", "m"))
                print(mm)
                print(m)
                if mm < m:  # 留下mm
                    with open(path + i, 'rb') as r:
                        read = r.read()
                    os.remove(path + i.replace("mm", "m"))
                    with open(path + i.replace("mm", "m"), "wb") as w:
                        w.write(read)
                else:
                    os.remove(path + i)
            except FileNotFoundError:
                os.rename(path + i, path + i.replace("mm", "m"))


if __name__ == '__main__':
    pass
    # path = "./resources/"
    # for i in os.listdir(path):
    #     if "mm" in str(i):
    #         print(path + i)
    #         print(path + i.replace("mm", "m"))  # m路径:path + i.replace("mm", "m")
    #         try:
    #             mm = get_size(path + i)
    #             m = get_size(path + i.replace("mm", "m"))
    #             print(mm)
    #             print(m)
    #             if mm < m:  # 留下mm
    #                 with open(path + i, 'rb') as r:
    #                     read = r.read()
    #                 os.remove(path + i.replace("mm", "m"))
    #                 with open(path + i.replace("mm", "m"), "wb") as w:
    #                     w.write(read)
    #             else:
    #                 os.remove(path + i)
    #         except FileNotFoundError:
    #             os.rename(path + i, path + i.replace("mm", "m"))

    # pngquantOperation("./resources/")
    # pngquantSystem("./resources/")
    # path = "./resources/"
    # for i in os.listdir(path):
    #     if ".jpg" in str(i):
    #         os.remove(path + i)
    #     if ".png" in str(i) and str(i)[0] == "m":
    # #         os.remove(path + i)
    # PNG_JPG("./resources/m99.png")
    # JPG_PNG("./resources/m99.jpg")
    # zipPNG("./resources/m99h.png")
    # PNG_JPG("./resources/m99hnew.png")
    # JPG_PNG("./resources/m99hnew.jpg")
    # zipPNG("./resources/m99hnewh.png")
    # compress_image("./resources/m99.png")
    # PNG_JPG("./resources/m99-out.png")
    # JPG_PNG("./resources/m99-out.jpg")
    # zipPNG("./resources/m99-outh.png")

#
# if __name__ == '__main__':
#     # zipPNG("./resources/m1.png")
#     # zipPNGs("./resources/")
#     PNG_JPG("./resources/m1.png")

# def get_outfile(infile, outfile):
#     if outfile:
#         return outfile
#     dirs, suffix = os.path.splitext(infile)
#     outfile = '{}-out{}'.format(dirs, suffix)
#     return outfile
#
#
# def compress_image(infile, outfile='', mb=150, step=10, quality=80):
#     """不改变图片尺寸压缩到指定大小
#     :param infile: 压缩源文件
#     :param outfile: 压缩文件保存地址
#     :param mb: 压缩目标，KB
#     :param step: 每次调整的压缩比率
#     :param quality: 初始压缩比率
#     :return: 压缩文件地址，压缩文件大小
#     """
#     o_size = get_size(infile)
#     if o_size <= mb:
#         return infile
#     outfile = get_outfile(infile, outfile)
#     while o_size > mb:
#         im = PIL.Image.open(infile)
#         im.save(outfile, quality=quality)
#         if quality - step < 0:
#             break
#         quality -= step
#         o_size = get_size(outfile)
#     return outfile, get_size(outfile)
# -----------------
# def pngquantOperation(path: str):
#     if path[0] == ".":
#         path = os.path.abspath("./").replace("\\", "/") + path[1:]
#     for i in os.listdir(path):
#         if ".png" in i:
#             print(path + str(i))
#             pngquant_compress(str(path + str(i)), force=True, quality=50)
#
#
# def pngquantSystem(path: str):
#     if path[0] == ".":
#         path = os.path.abspath("./").replace("\\", "/") + path[1:]
#         for i in os.listdir(path):
#             if ".png" in i:
#                 print(path + str(i))
#                 cmdPngquantCompress(path + str(i))
